package com.dtjd.playcoinmonkey.activities.main;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;

import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.activities.NoticeActivity;
import com.dtjd.playcoinmonkey.activities.RecommendDetailActivity;
import com.dtjd.playcoinmonkey.activities.SearchActivity;
import com.dtjd.playcoinmonkey.adapter.RecommendListAdapter;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.bean.RecommendListBean;
import com.dtjd.playcoinmonkey.databinding.FragmentRecommendBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RecommendFragment extends Fragment {
    private FragmentRecommendBinding binding;
    private RecommendListAdapter adp;
    private final List<RecommendListBean> data=new ArrayList<>();
    private int current=1;
    private MainActivity activity;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentRecommendBinding.inflate(inflater, container, false);
        activity= (MainActivity) requireActivity();
        adp=new RecommendListAdapter(activity,data);
        binding.recommendList.setAdapter(adp);
        binding.recommendRefresh.setRefreshHeader(new ClassicsHeader(activity));
        binding.recommendRefresh.setRefreshFooter(new ClassicsFooter(activity));
        binding.recommendRefresh.setOnRefreshListener(refreshLayout -> {
            current=1;
            refresh(refreshLayout,null);
        });
        binding.recommendRefresh.setOnLoadMoreListener(refreshLayout -> refresh(null,refreshLayout));
        binding.recommendNoticeDetail.setOnClickListener(view -> {
            Intent intent=new Intent(activity, NoticeActivity.class);
            intent.putExtra("title",getResources().getString(R.string.warn));
            intent.putExtra("isWarn",false);
            startActivity(intent);
        });
        binding.recommendList.setOnItemClickListener((adapterView, view, i, l) -> {

            Pair<View,String> pair1 = new Pair<>(view.findViewById(R.id.item_recomment_account), ViewCompat.getTransitionName(view.findViewById(R.id.item_recomment_account)));
            Pair<View,String> pair2 = new Pair<>(view.findViewById(R.id.item_home_content),ViewCompat.getTransitionName(view.findViewById(R.id.item_home_content)));


            MyApplication.recommendBean=data.get(i);
            startActivity(new Intent(activity, RecommendDetailActivity.class),ActivityOptions.makeSceneTransitionAnimation(activity,pair1,pair2).toBundle());
        });
        binding.recommendSearch.setOnClickListener(view -> startActivity(new Intent(activity, SearchActivity.class), ActivityOptions.makeSceneTransitionAnimation(activity, binding.recommendSearch, "search").toBundle()));
        refresh(null,null);
        return binding.getRoot();
    }
    private void refresh(RefreshLayout refreshLayout,RefreshLayout loadmorelayout) {
        List<HttpParaBean> para=new ArrayList<>();
        para.add(new HttpParaBean("getOne","true"));
        Network.post(para, "wbhMain/getNotice", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        JSONArray ja = new JSONObject(Objects.requireNonNull(response.body()).string()).getJSONArray("datalist");
                        if (ja.length()>0) binding.recommendNotice.setText(ja.getJSONObject(0).getString("content"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    if (loadmorelayout!=null&&refreshLayout==null) current++;
                    if (refreshLayout!=null&&loadmorelayout==null) current=1;
                    ArrayList<HttpParaBean> list=new ArrayList<>();
                    list.add(new HttpParaBean("current",String.valueOf(current)));
                    list.add(new HttpParaBean("size", "5"));
                    Network.post(list, "wbhMain/recommendPosts", new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            activity.runOnUiThread(() -> {
                                try {
                                    JSONObject jo1=new JSONObject(response.body().string());
                                    JSONArray ja = jo1.getJSONArray("datalist");
                                    if (loadmorelayout==null) data.clear();
                                    if (ja.length()!=0){
                                        for (int i = 0; i < ja.length(); i++){
                                            JSONObject jo = ja.getJSONObject(i);
                                            JSONArray jo_imgs = jo.getJSONArray("imgs");
                                            String img_url="";
                                            if (jo_imgs.length()>0) img_url= jo_imgs.getString(0);
                                            data.add( new RecommendListBean(jo.getString("id"),jo.getInt("bp_click_number"), jo.getString("bp_content"), jo.getString("bp_title"), img_url, jo.getString("wb_nickname"), jo.getString("wb_url"), jo.getString("time")));
                                        }
                                        adp.notifyDataSetChanged();
                                    }
                                    if (refreshLayout!=null)refreshLayout.finishRefresh(0);
                                    if (loadmorelayout!=null)loadmorelayout.finishLoadMore(0);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                });
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}